package com.yoyo.itravel.web.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.yoyo.itravel.bean.Sight;
import com.yoyo.itravel.bean.SightOrder;
import com.yoyo.itravel.bean.TicketTypeDetail;
import com.yoyo.itravel.bean.User;
import com.yoyo.itravel.constants.AlipayConfigConstant;
import com.yoyo.itravel.constants.DateFormatConstant;
import com.yoyo.itravel.constants.UserConstant;
import com.yoyo.itravel.exceptions.SightCompanyException;
import com.yoyo.itravel.exceptions.SightException;
import com.yoyo.itravel.exceptions.SightOrderException;
import com.yoyo.itravel.exceptions.TicketTypeDetailException;
import com.yoyo.itravel.service.ISightCompanyService;
import com.yoyo.itravel.service.ISightOrderService;
import com.yoyo.itravel.service.ISightService;
import com.yoyo.itravel.service.ITicketTypeDetailService;
import com.yoyo.itravel.utils.DateUtils;
import com.yoyo.itravel.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description 景点门票预定支付控制层
 * @Author HZX
 * @Version 1.0
 * @Date 2020/6/19 11:03
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private ITicketTypeDetailService ticketTypeDetailService;
    @Autowired
    private ISightOrderService sightOrderService;
    @Autowired
    private ISightCompanyService sightCompanyService;
    @Autowired
    private ISightService sightService;

    /**
     * @Description 支付
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/pay")
    protected void pay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得数据
        String trip_date = request.getParameter("trip_date");
        String real_name = request.getParameter("real_name");
        String phone = request.getParameter("phone");
        String id_card = request.getParameter("id_card");
        String order_num = request.getParameter("order_num");
        String detailTypeId = request.getParameter("detailTypeId");

        // 将detailTypeId放入session
        request.getSession().setAttribute("detailTypeId", detailTypeId);

        // 构建景点订单对象
        SightOrder sightOrder = new SightOrder();
        // 获得当前登录用户的信息
        User user = (User) request.getSession().getAttribute(UserConstant.USER);
        // 订单随机UUID
        String randomUUID = "";
        // 声明预定的门票具体类型对象
        TicketTypeDetail ticketDetailType = null;
        BigDecimal totalPrice = null;

        try {
            // 获得预定的门票具体类型对象
            ticketDetailType = ticketTypeDetailService.findByTicketDetailTypeId(detailTypeId);

            if (ticketDetailType != null) {
                totalPrice = ticketDetailType.getOrderPrice().multiply(new BigDecimal(order_num));
            }

            // 景点订单对象设置属性
            /** 补充属性 **/
            // 订单创建时间
            sightOrder.setCreateTime(new Date());
            // 订单总金额
            sightOrder.setPayAmount(totalPrice);
            sightOrder.setTripDate(DateUtils.parseStrToDate(trip_date, DateFormatConstant.DATE_FORMAT_YYYY_MM_DD));
            sightOrder.setRealName(real_name);
            sightOrder.setPhone(phone);
            sightOrder.setIDCard(id_card);
            sightOrder.setOrderNum(Integer.parseInt(order_num));
            // 添加当前登录用户的id
            sightOrder.setUserId(user.getUserId());
            // 生成订单随机UUID，用作订单id
            randomUUID = StringUtils.getRandomUUID();
            sightOrder.setOrderId(randomUUID);
            // 预定的门票具体类型
            sightOrder.setDetailTypeId(detailTypeId);
            sightOrder.setTicketTypeDetail(ticketDetailType);
            // 设置订单的状态为1：未支付状态
            sightOrder.setOrderStatus(1);
            // 设置支付类型为1：支付宝支付
            sightOrder.setPayType(1);
            sightOrderService.createSightOrder(sightOrder);
        } catch (SightOrderException e) {
            e.printStackTrace();
        } catch (TicketTypeDetailException e) {
            e.printStackTrace();
        }

        /** 1.订单确认 **/
        /** 2.订单提交至支付宝 **/
        /** 3.支付宝回调（notify 或 return） **/
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigConstant.GATEWAY_URL, AlipayConfigConstant.APP_ID, AlipayConfigConstant.MERCHANT_PRIVATE_KEY, "json", AlipayConfigConstant.CHARSET, AlipayConfigConstant.ALIPAY_PUBLIC_KEY, AlipayConfigConstant.SIGN_TYPE);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfigConstant.RETURN_URL);
        alipayRequest.setNotifyUrl(AlipayConfigConstant.NOTIFY_URL);

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = randomUUID;
        // 付款金额，必填
        String total_amount = totalPrice == null ? "" : totalPrice.toString();
        // 订单名称，必填
        String subject = ticketDetailType.getDetailTypeName();
        // 景点商家支付宝UID，如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";
        try {
            sellerId = sightCompanyService.findAlipayUIDByDetailTypeId(detailTypeId);
        } catch (SightCompanyException e) {
            e.printStackTrace();
        }
        // 商品描述，可空
        String body = ticketDetailType.getDescription() == null ? "无" : ticketDetailType.getDescription();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"sellerId\":\"" + sellerId + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 请求
        String result;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + AlipayConfigConstant.CHARSET);

            response.getWriter().write(result); // 直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            response.getWriter().write("捕获异常出错");
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    /**
     * @Description 再次发起支付
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/payAgain")
    protected void payAgain(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获得订单号
        String orderId = request.getParameter("orderId");
        SightOrder sightOrder = null;
        TicketTypeDetail ticketTypeDetail = null;
        try {
            sightOrder = sightOrderService.findByOrderId(orderId);
            if (sightOrder != null) {
                // 获得具体门票类型对象
                ticketTypeDetail = ticketTypeDetailService.findByTicketDetailTypeId(sightOrder.getDetailTypeId());
            }

        } catch (SightOrderException e) {
            e.printStackTrace();
        } catch (TicketTypeDetailException e) {
            e.printStackTrace();
        }

        if (sightOrder == null || ticketTypeDetail == null) {
            return;
        }

        /** 1.订单确认 **/
        /** 2.订单提交至支付宝 **/
        /** 3.支付宝回调（notify 或 return） **/
        // 获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigConstant.GATEWAY_URL, AlipayConfigConstant.APP_ID, AlipayConfigConstant.MERCHANT_PRIVATE_KEY, "json", AlipayConfigConstant.CHARSET, AlipayConfigConstant.ALIPAY_PUBLIC_KEY, AlipayConfigConstant.SIGN_TYPE);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfigConstant.RETURN_URL);
        alipayRequest.setNotifyUrl(AlipayConfigConstant.NOTIFY_URL);

        // 商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = sightOrder.getOrderId();
        // 付款金额，必填
        String total_amount = sightOrder.getPayAmount() == null ? "" : sightOrder.getPayAmount().toString();
        // 订单名称，必填
        String subject = ticketTypeDetail.getDetailTypeName();
        // 商品描述，可空
        String body = ticketTypeDetail.getDescription() == null ? "无" : ticketTypeDetail.getDescription();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        // 请求
        String result;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + AlipayConfigConstant.CHARSET);
            System.out.println(result);
            response.getWriter().write(result); // 直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            response.getWriter().write("捕获异常出错");
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    /**
     * @Description 订单支付结果---注意：异步回调需要为公网环境，且不能被拦截才会被调用【即外网可以访问】，支付宝的服务器在支付状态改变后会主动访问我们的服务器
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/alipayNotify")
    protected void alipayNotify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("fffffffffffffffffffffffffffffffffffffffffffffff");
        // 获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //调用SDK验证签名
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfigConstant.ALIPAY_PUBLIC_KEY, AlipayConfigConstant.CHARSET, AlipayConfigConstant.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

       /* 实际验证过程建议商户务必添加以下校验：
       1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
       2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
       3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
       4、验证app_id是否为该商户本身。
       */
        // 验证成功
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println(trade_no);
            System.out.println(trade_status);
            System.out.println(total_amount);

            switch (trade_status) { // 判断交易结果
                case "TRADE_FINISHED": // 交易结束并不可退款
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序
                    //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知

                    break;
                case "TRADE_SUCCESS": // 交易支付成功
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序
                    //注意：
                    //付款完成后，支付宝系统发送该交易状态通知
                    try {
                        // 支付成功，修改订单状态【待出行】
                        sightOrderService.updateOrderStatus(out_trade_no, 2);
                        // 添加订单交易号
                        sightOrderService.addTradeNoByOrderId(out_trade_no, trade_no);
                        // 对应的景点门票销量增加
                        SightOrder sightOrder = sightOrderService.findByOrderId(out_trade_no);
                        // 开启一个定时器--出行后修改订单状态为待点评
                        sightOrderService.preCommentTimer(sightOrder);
                        Sight sight = ticketTypeDetailService.findSight(sightOrder.getDetailTypeId());
                        sightService.updateSellCount(sight.getSightId(), sightOrder.getOrderNum());
                    } catch (SightOrderException e) {
                        e.printStackTrace();
                    } catch (TicketTypeDetailException e) {
                        e.printStackTrace();
                    } catch (SightException e) {
                        e.printStackTrace();
                    }

                    break;
                case "TRADE_CLOSED": // 未付款交易超时关闭或支付完成后全额退款
                    break;
                case "WAIT_BUYER_PAY": // 交易创建并等待买家付款
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * @Description 退款
     *
     * @Param request
     * @Param response
     * @Return void
     */
    @RequestMapping("/refund")
    protected void refund(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获得订单号
        String orderId = request.getParameter("orderId");
        SightOrder sightOrder = null;
        TicketTypeDetail ticketTypeDetail = null;

        try {
            sightOrder = sightOrderService.findByOrderId(orderId);
            if (sightOrder != null) {
                // 获得具体门票类型对象
                ticketTypeDetail = ticketTypeDetailService.findByTicketDetailTypeId(sightOrder.getDetailTypeId());
            }

        } catch (SightOrderException e) {
            e.printStackTrace();
        } catch (TicketTypeDetailException e) {
            e.printStackTrace();
        }

        if (sightOrder == null || ticketTypeDetail == null) {
            return;
        }

        try {
            //获得初始化的AlipayClient
            //URL APPID RSA_PRIVATE_KEY JSON CHARSET ALIPAY_PUBLIC_KEY  SIGNTYPE
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigConstant.GATEWAY_URL, AlipayConfigConstant.APP_ID, AlipayConfigConstant.MERCHANT_PRIVATE_KEY, "json", AlipayConfigConstant.CHARSET, AlipayConfigConstant.ALIPAY_PUBLIC_KEY, AlipayConfigConstant.SIGN_TYPE);
            //设置请求参数
            AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = sightOrder.getOrderId();
            //支付宝交易号
            String trade_no = sightOrder.getTradeNo();
            //请二选一设置
            //需要退款的金额，该金额不能大于订单金额，必填
            String refund_amount = sightOrder.getPayAmount() + "";
            String refund_reason = "fjfdf";
            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//            String out_request_no = aliOrderDTO.getRefundNum();
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"trade_no\":\"" + "\","
                    + "\"refund_amount\":\"" + refund_amount + "\","
                    + "\"refund_reason\":\"" + refund_reason + "\","
                    + "\"out_request_no\":\"" + "\"}");

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + AlipayConfigConstant.CHARSET);
            if (result.contains("Success")) { // 退款成功
                sightOrderService.updateOrderStatus(orderId, 4);
            }
            response.getWriter().write(result); // 直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
            String result = "1";
            response.setContentType("text/html;charset=utf-8");
            try {
                response.getWriter().write(result);// 直接将完整的表单html输出到页面
                response.getWriter().flush();
                response.getWriter().close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
    }

}
